/**
 * Created by zhouli on 18/2/28
 * Email li.zhou@huilianyi.com
 */
import React from 'react';
import {getUrlSearchParams, deepCopy} from 'share/common';
import httpFetch from 'share/httpFetch';
import config from 'config';
import constants from 'share/constants';
import {message} from 'antd';

const unifiedJumpConfig = constants.unifiedJumpConfig;

export function sso_huilianyi(success, error) {
  let CURRENT_LOCALHOST = window.location.href;
  //检查有没有code，如果有，直接去获取token
  let Request = getUrlSearchParams(); //实例化
  if (Request.code) {
    //这个code参数能否设置复杂一点，比如设置为sso_code
    //有些页面如果有code参数会有冲突
    httpFetch.login(Request.code, Request.code, 'sso').then((data) => {
      //单点登录之后，不是直接就成功回调，看一下是否有业务需求
      //如果有业务，就直接重定向到对应的页面
      if (is_need_redirect(CURRENT_LOCALHOST) === "mailApprove") {
        //邮件审批重定向
        redirect_by_url_for_mail_approve(CURRENT_LOCALHOST);
      } else if (is_need_redirect(CURRENT_LOCALHOST) === "something") {
        //先写在这里，暂时不会走这个逻辑
        redirect_by_url_for_something(CURRENT_LOCALHOST);
      } else {
        success(data);
      }
    }).catch((err) => {
      error(err);
    })
  } else {
    //去拿登录code
    if (Request.mailApprove) {
      //邮件审批的情况
      if (window.location.href.indexOf("ef.huilianyi.com") > -1 ||
        window.location.href.indexOf("stageef.huilianyi.com") > -1 ||
        window.location.href.indexOf("efsit.huilianyi.com") > -1) {
        //如果是英孚
        window.location.href = config.ssoUrl + '/sso/login?redirect_url=' +
          CURRENT_LOCALHOST + '&origin_url=' + CURRENT_LOCALHOST;
      } else {
        //如果是其他,要保存
        //只要有origin_url_for_mail_approve这个参数，还需要去登录那边做控制，直接跳入到审批界面
        window.location.href = "/?origin_url_for_mail_approve=" + CURRENT_LOCALHOST;
      }
    } else {
      window.location.href = config.ssoUrl + '/sso/login?redirect_url=' +
        CURRENT_LOCALHOST + '&origin_url=' + CURRENT_LOCALHOST;
    }
  }
}

//邮件审批重定向
export function redirect_by_url_for_mail_approve(url) {
  window.localStorage.setItem('mail_approve', url ? url : window.location.href);
  let Request = getUrlSearchParams(url); //实例化
  if (Request.origin_url_for_mail_approve) {
    let url = Request.origin_url_for_mail_approve + "&targetParams=" + Request.targetParams;
    Request = getUrlSearchParams(url);
  }
  let redirectURL = '/main/dashboard';
  let targetParams = JSON.parse(atob(Request.targetParams));
  // 解码之后,格式对象
  // targetParams={
  //   targetState: "site.app.expense_report_detail_approve",
  //   approverOID: "028a86a3-4421-4413-aa57-156aef1ca8e2",
  //   entityOID: "23e2ab2a-d03e-4867-9d8b-ec2d357e9313"
  // }
  if (targetParams && targetParams.targetState) {
    if (targetParams.targetState.indexOf('site.app.expense_report_detail_approve') > -1) {
      //报销单详情-自测通过
      redirectURL = '/main/approve/approve-expense-report/approve-expense-report-detail/' +
        targetParams.entityOID + "?approvePending=true&approverOID=" + targetParams.approverOID;
    } else if (targetParams.targetState.indexOf('site.app.custom_application_approver') > -1) {
      //申请单详情-自测通过
      redirectURL = '/main/approve/approve-request/approve-request-detail/' +
        targetParams.formOID + '/' + targetParams.entityOID + "?approving=true&approverOID=" + targetParams.approverOID;
    }  else if (targetParams.targetState.indexOf('site.app.loan') > -1) {
      //借款单 bug 37678
      // url: '/main/approve/approve-loan/approve-loan-detail/:formOID/:loanBillOID/:backType',
      // loanBillOID  用 entityOID
      // backType 写 'history'
      redirectURL = '/main/approve/approve-loan/approve-loan-detail/' +
        targetParams.formOID +
        '/' +
        targetParams.entityOID +
        "/history?approving=true&approverOID=" +
        targetParams.approverOID;
    }else if (targetParams.targetState.indexOf('site.app.form_approval_result') > -1) {
      //审批通过
      //这个逻辑，本次需求去掉了，只要上面两个逻辑即直接跳转到详情
    }
  }
  window.location.href = redirectURL;
}

//待办消息统一中转路由 task8792
export function redirect_by_url_for_approval_route(url) {
  let Request = getUrlSearchParams(url); //实例化
  let targetParams = null;
  try {
    targetParams = JSON.parse(atob(Request.targetParams));
  } catch (e) {
  }
  let messageType = Request.messageType;
  let targetUrl = generateUrlByTypeAndParams(messageType, targetParams, unifiedJumpConfig);
  if (targetUrl) {
    console.log("待办消息")
    window.localStorage.setItem('mail_approve', targetUrl);
    window.location.href = targetUrl;
  }
}

/**
 * 通过传入的 messageType，与targetParams，跳转的map关系，生成一个url
 * @param messageType  消息类型
 * @param targetParams  跳转需要的参数
 * @param urlMapping  跳转页面的map关系
 * @return url 返回目标url
 */
export function generateUrlByTypeAndParams(messageType, targetParams, urlMapping) {
  let item = _getTargetItem(messageType, urlMapping);

  if (item) {
    if (targetParams === null) {
      //说明没有参数
      return item.targetUrl;
    }
    let targetUrl = paramsIsOk(item, targetParams);
    if (targetUrl) {
      return targetUrl;
    } else {
      message.warn("参数不全，无法跳转");
      return null;
    }
  } else {
    message.warn("找不到对应的消息类型: " + messageType);
    return null;
  }

  //根据type获取对应的url
  function _getTargetItem(messageType, urlMapping) {
    for (let i = 0; i < urlMapping.length; i++) {
      if (_hasType(messageType, urlMapping[i].messageType)) {
        return urlMapping[i];
      }
    }
    return null;

    function _hasType(messageType, typeArr) {
      for (let i = 0; i < typeArr.length; i++) {
        if (messageType === typeArr[i]) {
          return true;
        }
      }
      return false
    }
  }

  // 判断跳转的参数是否完整,
  // 不完整返回false
  // 完整就拼接参数并返回目标url
  function paramsIsOk(item, targetParams) {
    let requireParams = item.requireParams;
    let redirectURL = item.targetUrl;
    if (requireParams.length === 0) {
      return redirectURL;
    } else {
      for (let i = 0; i < requireParams.length; i++) {
        if (!targetParams[requireParams[i]]) {
          return false;
        }
      }
      //条件满足
      for (let i = 0; i < requireParams.length; i++) {
        if (targetParams[requireParams[i]]) {
          redirectURL = redirectURL.replace(":" + requireParams[i], targetParams[requireParams[i]]);
        }
      }
      return redirectURL;
    }
  }
}

//其他需求重定向
export function redirect_by_url_for_something() {
}

//登录之后：判断是否需要重新定向
export function is_need_redirect(url) {
  let Request = getUrlSearchParams(url); //实例化
  if (Request.mailApprove) {
    return "mailApprove";
  } else {
    return false;
  }
}

